package com.lxm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lxm.entity.Admin;
import com.lxm.entity.ResultEntity;
import com.lxm.service.IAdminRoleService;
import com.lxm.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lxm
 * @since 2021-11-18
 */
@RestController
@RequestMapping("/user")
public class AdminController {
    @Autowired
    private IAdminService as;
    @Autowired
    private IAdminRoleService ars;

    //用户登陆
    @GetMapping("/login")
    public ResultEntity<Admin>login(String username, String password, HttpSession session){
        Admin user = as.login(username, password);
        if(user==null){
            return ResultEntity.error("error");
        }else{
            session.setAttribute("user",user);
            return ResultEntity.ok(user);
        }

    }

    //用户列表展示
    @GetMapping("showAll")
    public ResultEntity<List<Admin>> showAllUsers(){
        List<Admin> list = as.list();
        if(list==null){
            return ResultEntity.error("error");
        }else{
            return ResultEntity.ok(list);
        }
    }

    //添加用户
    @PostMapping("/insert")
    public ResultEntity addUser(@RequestBody Admin user){
        as.save(user);
        return ResultEntity.ok();
    }

    //删除用户(自动就逻辑删除了，把状态改成了0，未激活)
    @DeleteMapping("/delete/{id}")
    public ResultEntity deleteUser(@PathVariable int id){
        boolean b = as.removeById(id);
        if(b){
            return ResultEntity.ok();
        }
        return ResultEntity.error("删除失败");

    }
    //根据用户标记查询用户信息
    @GetMapping("selectById/{userId}")
    public ResultEntity<Admin> selectById(@PathVariable int userId){
        Admin user = as.getById(userId);
        if(user==null){
            return ResultEntity.error("该用户不存在");
        }
        return ResultEntity.ok(user);
    }

    //修改用户信息，只有已激活的用户可以修改信息，也就是用户名和密码
    @PutMapping("/update")
    public ResultEntity updateUser(@RequestBody Admin user){
        boolean b = as.updateById(user);
        if(b){
            return ResultEntity.ok();
        }else {
            return ResultEntity.error("修改用户失败");
        }
    }
    //查看该用户拥有哪些角色
    @GetMapping("/selectRoleId/{userId}")
    public ResultEntity<List<Integer>> selectRoleByUserId(@PathVariable int userId){
        List<Integer> integers = ars.selectAllRoleIdByUserId(userId);
        return  ResultEntity.ok(integers);
    }


}

